import { Inject, Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { createProxyMiddleware } from 'http-proxy-middleware';
import AuthApi from '../api/auth.api';
import { GatewayService } from '../gateway.service';
import R from 'libs/common/utils/R';
import config from '../../config/index';
@Injectable()
export class ProxyMiddleware implements NestMiddleware {
  constructor(
    @Inject(AuthApi) private readonly authApi: AuthApi,
    @Inject(GatewayService) private readonly gatewayService: GatewayService,
  ) {}

  async use(req: Request, res: Response, next: NextFunction) {
    const service = req.originalUrl.split('/')[1];
    const api = req.originalUrl.replace(`/${service}`, '');
    const hasAuth = await this.authApi.validateIdentity({
      token: req.headers.token as string,
      service: service,
      api: api,
    });
    if (hasAuth) {
      const path = await this.gatewayService.getOneHostPath(service);
      req.url = 'http://127.0.0.1:' + config.port + api;
      const apiProxy = createProxyMiddleware({
        target: path,
        changeOrigin: true,
      });
      apiProxy(req, res, next);
    } else {
      return res.send(R.error('无权限！'));
    }
  }
}
